import XEUtils from 'xe-utils'
import _ from 'lodash'
export default {
  props: {
    api: {
      type: Object,
      required: true,
      default: function () {
        return {}
      }
    },
    columns: {
      type: Array,
      default: function () {
        return []
      }
    },
    formSetting: {
      type: Object,
      default: function () {
        return {}
      }
    },
    formItemSetting: {
      type: Array,
      default: function () {
        return []
      }
    },
    paging: {
      type: Boolean,
      default: true
    },
    primaryKey: {
      type: String,
      default: 'id'
    },
    editRules: {
      type: Object,
      default: function () {
        return {}
      }
    },
    sortConfig: {
      type: Object,
      default: function () {
        return {}
      }
    }
  },
  watch: {
    columns (value) {
      this.$nextTick(() => this.loadColumn(value))
    }
  },
  data () {
    return {
      // 分页
      search: {},
      active: true,
      pagination: {
        current: 1,
        size: 25,
        total: 1
      },
      table: null,
      tableData: [],
      tableColumns: [],
      diglogBrowseConf: {
        dialogVisible: false,
        columns: [],
        insertRecords: [],
        removeRecords: [],
        updateRecords: [],
        updateFields: []
      },
      selectRow: null,
      loading: true,
      // 主体表格列过滤
      columnsFilter: {
        options: []
      }
    }
  },
  created () {
    this.fetchTableData()
  },
  mounted () {
    this.table = this.$refs.table
    if (this.columns && this.columns.length) {
      this.loadColumn(this.columns)
    }
  },
  methods: {
    loadColumn (columns) {
      this.tableColumns = XEUtils.clone(columns)
      var index = this.tableColumns.findIndex(column => {
        return column.key === 'operation'
      })
      if (index < 0) {
        this.tableColumns.push({ key: 'operation', title: '操作', width: '120', slots: { default: 'operation' } })
      }
      const { $scopedSlots } = this.table
      XEUtils.eachTree(this.tableColumns, column => {
        if (!column.key) {
          column.key = _.uniqueId('column_')
        }
        if (column.slots) {
          XEUtils.each(column.slots, (func, name, slots) => {
            if (!XEUtils.isFunction(func)) {
              if ($scopedSlots[func]) {
                slots[name] = $scopedSlots[func]
              } else {
                slots[name] = null
                console.error('vxe.error.notSlot', [func])
              }
            }
          })
        }
      })
      this.table.loadColumn(this.tableColumns)
      this.columnsFilter.options = _.cloneDeep(this.tableColumns.filter(e => e.if !== false))
    },
    reloadColumn (columns) {
      this.table.clearAll()
      return this.loadColumn(columns)
    },
    fetchTableData () {
      let param = this.paging ? {
        'pageNum': this.pagination.current,
        'pageSize': this.pagination.size
      } : {}
      Object.assign(param, this.search)
      if (this.api.index) {
        this.api.index(param).then(res => {
          this.tableData = res.list
          this.pagination.current = res.pageNum
          this.pagination.total = res.total
          this.loading = false
        })
      }
    },
    saveTableData () {
      const { insertRecords, removeRecords } = this.table.getRecordset()
      let param = {
        insert: insertRecords,
        remove: removeRecords.map(item => { return item[this.primaryKey] }),
        update: this.getUpdateFields()
      }
      console.log('param', param)
      this.api.save(param).then(res => {
        this.$message({
          type: 'success',
          message: '保存成功!'
        })
      })
    },
    // 刷新
    handleRefresh () {
      this.fetchTableData()
    },
    // 设置
    handleSetting () {
      this.$refs.columnFilter.start()
    },
    // 导出
    handleExport () {
      console.log('导出')
    },
    // 打印
    handlePrint () {
      console.log('打印')
    },
    // 搜索
    handleSearch () {
      this.fetchTableData()
    },
    // 重置搜索
    resetOfSearch () {
      this.search = {}
    },
    // 上移
    handleMoveUpRow () {
      let row = this.selectRow
      let table = this.table
      var sort = row.sort
      let fullData = table.tableFullData
      var index = fullData.findIndex(item => item._XID === row._XID)
      if (index > 0) {
        let tempRow = fullData[index - 1]
        row.sort = tempRow.sort
        tempRow.sort = sort
        fullData.splice(index, 1)
        fullData.splice(index - 1, 0, row)
        table.updateData()
      }
    },
    // 下移
    handleMoveDownRow () {
      let row = this.selectRow
      let table = this.table
      var sort = row.sort
      let fullData = table.tableFullData
      var index = fullData.findIndex(item => item._XID === row._XID)
      if (index < fullData.length - 1) {
        let tempRow = fullData[index + 1]
        row.sort = tempRow.sort
        tempRow.sort = sort
        fullData.splice(index, 1)
        fullData.splice(index + 1, 0, row)
        table.updateData()
      }
    },
    // table添加行
    async handleAddRow (row) {
      let table = this.table
      var sort = row ? row.sort : 1
      let record = {
        sort: sort
      }
      let { row: newRow } = await table.insertAt(record, row)
      var fullData = table.tableFullData
      var index = fullData.findIndex(item => item._XID === newRow._XID)
      for (let i = index + 1; i < fullData.length; i++) {
        fullData[i].sort += 1
      }
      await table.setActiveCell(newRow)
    },
    // table删除行
    handleDeleteRow (row) {
      if (row) {
        this.$YConfirm('删除').then(() => {
          this.table.remove(row)
        })
      } else {
        let selectRecords = this.table.getCheckboxRecords()
        if (selectRecords.length) {
          this.$YConfirm('删除').then(() => {
            this.table.removeCheckboxRow()
          })
        } else {
          this.$message('未选中记录')
        }
      }
    },
    handleCurrentChange ({ row }) {
      this.selectRow = row
    },
    onColumnFilterChange (columns) {
      this.reloadColumn(columns)
    },
    handlePageChange ({ currentPage, pageSize }) {

    },
    // 重置table数据
    handleRevertRow () {
      let selectRecords = this.table.getCheckboxRecords()
      if (selectRecords.length) {
        this.$YConfirm('还原').then(() => {
          selectRecords.forEach(row => {
            this.table.revertData(row)
          })
        })
      } else {
        this.$YConfirm('还原').then(() => {
          this.table.revertData()
        })
      }
    },
    // 保存
    handleTableSave () {
      this.saveTableData()
    },
    // 浏览
    handleDialogBrowseVisible () {
      const { insertRecords, removeRecords, updateRecords } = this.table.getRecordset()
      this.diglogBrowseConf = {
        insertRecords: insertRecords,
        removeRecords: removeRecords,
        updateRecords: updateRecords,
        updateFields: this.getUpdateFields(),
        columns: this.columns,
        dialogVisible: true
      }
    },
    getUpdateFields () {
      var table = this.table
      const { keepSource, tableFullData, treeConfig, treeOpts } = table
      // 在 v3 中必须要开启 keep-source
      if (!keepSource) {
        console.warn('vxe.error.reqProp', ['keep-source'])
      }
      if (keepSource) {
        let attr = []
        if (treeConfig) {
          XEUtils.eachTree(tableFullData, row => {
            var obj = this.isUpdateByRow(row)
            if (!XEUtils.isEmpty(obj)) {
              obj[this.primaryKey] = row[this.primaryKey]
              attr.push(obj)
            }
          }, treeOpts)
          return attr
        }

        tableFullData.forEach(row => {
          var obj = this.isUpdateByRow(row)
          if (!XEUtils.isEmpty(obj)) {
            obj[this.primaryKey] = row[this.primaryKey]
            attr.push(obj)
          }
        })
        return attr
      }
      return []
    },
    /**
   * 检查行或列数据是否发生改变
   * @param {Row} row 行对象
   * @param {String} field 字段名
   */
    isUpdateByRow (row) {
      var table = this.table
      let updateDataObj = {}
      const { visibleColumn, keepSource, treeConfig, treeOpts, tableSourceData, fullDataRowIdData } = table
      if (keepSource) {
        let oRow, property
        const rowid = table.getRowid(row)
        // 新增的数据不需要检测
        if (!fullDataRowIdData[rowid]) {
          return false
        }
        if (treeConfig) {
          const children = treeOpts.children
          const matchObj = XEUtils.findTree(tableSourceData, item => rowid === table.getRowid(item), treeOpts)
          row = Object.assign({}, row, { [children]: null })
          if (matchObj) {
            oRow = Object.assign({}, matchObj.item, { [children]: null })
          }
        } else {
          const oRowIndex = fullDataRowIdData[rowid].index
          oRow = tableSourceData[oRowIndex]
        }
        if (oRow) {
          for (let index = 0, len = visibleColumn.length; index < len; index++) {
            property = visibleColumn[index].property
            if (property && !this.eqCellValue(oRow, row, property)) {
              updateDataObj[property] = row[property]
            }
          }
        }
      }
      return updateDataObj
    },
    eqCellValue (row1, row2, field) {
      const val1 = XEUtils.get(row1, field)
      const val2 = XEUtils.get(row2, field)
      if (this.eqCellNull(val1) && this.eqCellNull(val2)) {
        return true
      }
      if (XEUtils.isString(val1) || XEUtils.isNumber(val1)) {
        /* eslint-disable eqeqeq */
        return val1 == val2
      }
      return XEUtils.isEqual(val1, val2)
    },
    eqCellNull (cellValue) {
      return cellValue === '' || XEUtils.eqNull(cellValue)
    }
  }
}
